package com.pay.ioopos.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.dongqing.payreport.PayReport;
import com.pay.ioopos.Utils;
import com.pay.ioopos.service.ReportService;

import java.util.HashMap;

import okhttp3.Call;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class ReportReceiver extends BroadcastReceiver {
    private static Handler toastHandler = new Handler();
    private static Toast toast;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!ReportService.isInited()) {
            if (Utils.isApkInDebug(context)) {
                toast(context, "微信SDK未初始化，不上报数据");
            }
            return;
        }
        try {
            reportData(context, intent);
        } catch (Exception e) {
            Log.w(TAG, "微信SDK数据上报异常", e);
            toast(context, "微信SDK数据上报异常：" + e.getLocalizedMessage());
        }
    }

    private void reportData(Context context, Intent intent) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", intent.getStringExtra("out_trade_no"));
        map.put("transaction_id", intent.getStringExtra("transaction_id"));
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        PayReport.getInstance(context).reportData(map, new PayReport.ReportCallBack() {

            @Override
            public void Success(Call call, String s) {
                Log.d(TAG, "微信SDK数据上报成功");
                if (Utils.isApkInDebug(context)) {
                    toast(context, "微信SDK数据上报成功");
                }
            }

            @Override
            public void Failed(Exception e, Call call) {
                Log.w(TAG, "微信SDK数据上报失败", e);
                if (Utils.isApkInDebug(context)) {
                    toast(context, "微信SDK数据上报失败：" + e.getLocalizedMessage());
                }
            }
        });
    }

    private void toast(Context context, String msg) {
        if (null != toast) {
            toast.cancel();
        }
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        toastHandler.post(() -> {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
            toast.show();
        });
    }


}
